package fox.framework.rpc.client.message.request;


import fox.framework.rpc.converter.RpcMessageConverter;
import fox.framework.rpc.message.MappedRpcHeader;
import fox.framework.rpc.message.RpcHeader;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Collection;

/**
 * @author cuichao
 * @Description: RpcClientRequestAPI
 * @Date: create in 2021/1/22 21:38
 */
public class RpcClientRequestAPI implements RpcClientRequest {

    private String protocol;

    private String path;

    private RpcHeader header = new MappedRpcHeader();

    private Object[] source;

    private byte[] byteSource;

    private RpcMessageConverter converter;

    @Override
    public InputStream getInputStream() {
        if(source == null){
           return new ByteArrayInputStream(new byte[0]);
        }

        if(byteSource == null){
            encodeRequestBody();
        }
        return new ByteArrayInputStream(byteSource);
    }

    @Override
    public String getProtocol() {
        return protocol;
    }

    @Override
    public String getPath() {
        return path;
    }

    @Override
    public String getContentType() {
        return header.getHeader(RpcHeader.CONTENT_TYPE);
    }

    @Override
    public int getContentLength() {
          return Integer.valueOf(header.getHeader(RpcHeader.CONTENT_LENGTH));
    }


    @Override
    public String getHeader(String name) {
        return header.getHeader(name);
    }

    @Override
    public void setHeader(String name, String value) {
        header.setHeader(name,value);
    }

    @Override
    public Collection<String> getHeaderNames() {
        return header.getHeaderNames();
    }

    void setPath(String path){
        this.path = path;
    }

    void setProtocol(String protocol){
        this.protocol = protocol;
    }

    void setConverter(RpcMessageConverter converter){
        this.converter = converter;
    }

    void setRequestEntityBody(Object[] body){
        this.source = body;
    }

    void setContentType(String contentType){
        header.setHeader(RpcHeader.CONTENT_TYPE,contentType);
    }

    void encodeRequestBody(){
        if(source != null && source.length != 0) {
            byteSource = this.converter.encode(source);
            header.setHeader(RpcHeader.CONTENT_LENGTH,Integer.toString(byteSource.length));
        }else {
            header.setHeader(RpcHeader.CONTENT_LENGTH,Integer.toString(0));
        }

    }
}
